function formatTime(date) {
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()

    var hour = date.getHours()
    var minute = date.getMinutes()
    var second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatDate(date) {
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()

    return [year, month, day].map(formatNumber).join('-') 
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}
/**
 * 时间戳转化为年 月 日 时 分 秒
 * ts: 传入时间戳
 * format：返回格式，支持自定义，但参数必须与formateArr里保持一致
*/
function tsFormatTime(timestamp, format) {

    const formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
    let returnArr = [];

    let date = new Date(timestamp);
    let year = date.getFullYear()
    let month = date.getMonth() + 1
    let day = date.getDate()
    let hour = date.getHours()
    let minute = date.getMinutes()
    let second = date.getSeconds()
    returnArr.push(year, month, day, hour, minute, second);

    returnArr = returnArr.map(formatNumber);

    for (var i in returnArr) {
        format = format.replace(formateArr[i], returnArr[i]);
    }
    return format;

}

var rootDocment = '';
function req(url, data, cb) {
    wx.request({
        url: rootDocment + url,
        data: data,
        method: 'post',
        header: { 'Content-Type': 'application/x-www-form-urlencoded' },
        success: function (res) {
            return typeof cb == "function" && cb(res.data)
        },
        fail: function () {
            return typeof cb == "function" && cb(false)
        }
    })
}

function getReq(url, data, cb) {
    wx.request({
        url: rootDocment + url,
        data: data,
        method: 'get',
        header: { 'Content-Type': 'application/x-www-form-urlencoded' },
        success: function (res) {
            return typeof cb == "function" && cb(res.data)
        },
        fail: function () {
            return typeof cb == "function" && cb(false)
        }
    })
}

// 去前后空格
function trim(str) {
    return str.replace(/(^\s*)|(\s*$)/g, "");
}

// 提示错误信息
function isError(msg, that) {
    that.setData({
        showTopTips: true,
        errorMsg: msg
    })
}

// 清空错误信息
function clearError(that) {
    that.setData({
        showTopTips: false,
        errorMsg: ""
    })
}

module.exports = {
    formatTime: formatTime,
    formatDate: formatDate,
    tsFormatTime: tsFormatTime,
    req: req,
    trim: trim,
    isError: isError,
    clearError: clearError,
    getReq: getReq
}